from rest_framework import serializers

from oauth.models import OAuthQQUser
from oauth.utils import decode_sign_openid
from django_redis import get_redis_connection

from users.models import User


class OAuthQQUserSerializer(serializers.Serializer):
    password = serializers.CharField(min_length=8, max_length=20, label="密码")
    mobile = serializers.RegexField(label="手机号", regex=r'^1[3-9]\d{9}$')
    sms_code = serializers.CharField(min_length=6, max_length=6, label="短信")
    access_token = serializers.CharField(label="加密openid")


    def validate(self, attrs):
        # 1,校验openid
        openid = decode_sign_openid(attrs["access_token"])
        if not openid:
            raise serializers.ValidationError("openid错误")
            # 2.校验短信验证码
        mobile = attrs["mobile"]
        sms_code = attrs["sms_code"]

        redis_conn = get_redis_connection("code")
        redis_sms_code = redis_conn.get("sms_code_%s" % mobile)
        if not redis_sms_code:
            raise serializers.ValidationError("短信验证码过期")

        if sms_code != redis_sms_code.decode():
            raise serializers.ValidationError("短信验证码错误")
        # 3.校验密码
        user = None
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            pass
        else:
            # 判断密码是否正确
            if not user.check_password(attrs["password"]):
                raise serializers.ValidationError("密码错误")


         # 4，返回

        attrs["openid"] = openid
        attrs["user"] = user

        return attrs
    #2.重写create方法和openid
    def create(self,validated_data):
        #1.获取数据
        openid = validated_data["openid"]
        user = validated_data['user']
        #2.判断是否存在user
        if not user:
            user = User.objects.create_user(
                username=validated_data["mobile"],
                password=validated_data["password"],
                mobile=validated_data["mobile"]
            )
        #3.创建oauthqquser对象，绑定对象
        OAuthQQUser.objects.create(openid=openid,user=user)
        #返回
        return user